package com.mytravel

import android.os.Handler
import android.os.Looper
import com.amap.api.location.AMapLocation
import com.android.architecture.data.remote.HttpRequest
import com.android.architecture.helper.AppExecutors
import com.android.architecture.helper.Logger
import com.hjq.toast.ToastUtils
import com.locationlib.listener.OnLocationListener
import com.locationlib.utils.LocationUtils
import com.mytravel.MyApp.Companion.TAG
import org.json.JSONObject

/**
 * Created by SuQi on 2024/9/26.
 * Describe:
 */
object UploadHelper {

    private val httpRequest = HttpRequest()
    private val locationUtils = LocationUtils()
    private val HANDLER = Handler(Looper.getMainLooper())

    init {
        locationUtils.initLocation(MyApp.mApp)
        locationUtils.setLocationListener(object : OnLocationListener{
            override fun onLocationSucc(locationInfo: AMapLocation?) {
                if (locationInfo != null) {
                    startUpload(locationInfo.latitude.toString(), locationInfo.longitude.toString())
                }
            }

            override fun onLocationError(location: AMapLocation?) {
            }

            override fun onLocationRetryFailed() {
                ToastUtils.show("定位失败")
                goNextUpload()
            }
        })
    }

    fun uploadAddressInfo() {
        locationUtils.startLocation()
    }

    private fun startUpload(latitude:String , longitude:String) {
        AppExecutors.getInstance().io().execute {
            httpRequest.setUrl(AppCache.getUrl())
            val obj = JSONObject()
            obj.put(Constants.LATITUDE, latitude)
            obj.put(Constants.LONGITUDE, longitude)
            obj.put(Constants.SN, AppCache.getSn())
            val data = obj.toString()
            val response = httpRequest.postJson(data)
            Logger.e(TAG, "response:$response")
            AppCache.saveUploadTimes(AppCache.getUploadTimes() + 1)
            goNextUpload()
        }

    }

    private fun goNextUpload() {
        HANDLER.removeCallbacksAndMessages(null)
        HANDLER.postDelayed({
            uploadAddressInfo()
        }, AppCache.getIntervalTime() * 60 * 1000L)
    }

}